package club.pchome.controller;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import club.pchome.common.constant.SystemConstant;
import club.pchome.dto.Result;
import club.pchome.dto.UserInfoDto;
import club.pchome.model.AutoSign;
import club.pchome.model.UserInfo;
import club.pchome.service.AutoSignService;
import club.pchome.service.UserInfoService;
import club.pchome.util.DateUtil;
import club.pchome.util.JsoupSignAdm;

@RestController
public class AutoSignContoller extends BaseController{
	private final static SimpleDateFormat FMT_FN = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Autowired
	AutoSignService autoSignService;
	@Autowired
	UserInfoService userInfoService;
	@Autowired
	JsoupSignAdm signAdm;

	/**
	 *   核验用户状态
	 * @return
	 */
	@PostMapping("/checkAccountStatus")
	public Result<String> checkAccountStatus() {

		//首先获取 可以签到的账户
		List<AutoSign> list = autoSignService.checkAccountStatus();

		if(list.size() > 0) {

			for (AutoSign autoSign : list) {

				String JSESSIONID = ADMLOGIN(autoSign.getPhone() , autoSign.getPwd());

				long status = -1;
				if(!JSESSIONID.equals("10021")) {
					/***
					 * {"code":"200","errorCode":"SUCCESS","msg":"ok","data":{"time":"1560088105290"}}
					 */
					String Result = signAdm.JsoupToDataByCookie(SystemConstant.SIGN_STATUS , JSESSIONID);

					JSONObject jsonObject = JSONObject.parseObject(Result);
					JSONObject jsonObjectdata = jsonObject.getJSONObject("data");
					
					int code = jsonObject.getInteger("code");
					String errorCode = jsonObject.getString("errorCode");
					if(code == 200 && errorCode.equals("SUCCESS")) {
						
						long time = jsonObjectdata.getLong("time");
						
						status = -1;
						//只要能进来就是已经扫描了
						autoSign.setIsture(0);
						autoSign.setIsscan(0);
						autoSign.setSignstatus(0);
						if( time == 0 ) {//可签到 1970
							autoSign.setSignstatus(0);
							String signTime = FMT_FN.format(new Date(0));
							autoSign.setSigntime(Timestamp.valueOf(signTime));
							long nextTime = 1000 * 60 * 60 * 24;
							autoSign.setNextSigntime(Timestamp.valueOf(FMT_FN.format(nextTime)));
						}else {
							String signTime = FMT_FN.format(new Date(time));
							
							//获得时间等于当前时间就是已经签到了
							if(DateUtil.yyyyMMdd.format(new Date(time)).equals(DateUtil.yyyyMMdd.format(new Date()))) {
								//System.out.println("已经签到");
								autoSign.setSignstatus(1);
							}else {
								//	System.out.println("mei签到");
								autoSign.setSignstatus(0);
							}
							
							autoSign.setSigntime(Timestamp.valueOf(signTime));
							long nextTime = time + 1000 * 60 * 60 * 24;
							autoSign.setNextSigntime(Timestamp.valueOf(FMT_FN.format(nextTime)));
						}
						status = autoSignService.updateAccountInfo(autoSign);
					} else {
						logger.error("编号 : "+autoSign.getId()+" , loginName : " + autoSign.getPhone() +" , 核验失败!!! ");
					}

				}else {
					status = -1;
					//资料错误, 请更新资料
					autoSign.setIsture(2);
					autoSign.setIsscan(1);
					status = autoSignService.updateAccountInfo(autoSign);
				}

				if(status == -1) {
					logger.error("编号 : "+autoSign.getId()+" , loginName : " + autoSign.getPhone() +" , 更新时间失败!!! ");
				}

			}

			return Result.initSuccessResult("目前有 "+list.size() +" 核验扫描完成!");

		}else {
			return Result.initSuccessResult("没有需要核验的账户!");
		}

	}

	/**
	 * 签到
	 * @return
	 */
	@PostMapping("/signNew")
	public Result<String> signNew() {
		List<AutoSign> list = autoSignService.getAccountAndSignList();
		int COUNT = list.size();
		if(list.size() > 0) {

			for (AutoSign autoSign : list) {

				String JSESSIONID = ADMLOGIN(autoSign.getPhone() , autoSign.getPwd());

				/**
				 * error : {"msg":"请于2019-06-10 22:36:45后进行签到，24小时只能签到一次","code":"200125","errorCode":"CHECK_IN_ERROR"}
				 */
				String Result = signAdm.openSign(JSESSIONID);
				JSONObject ResultJson = JSONObject.parseObject(Result);
				int _code_1_ 	 = ResultJson.getInteger("code");
				if(_code_1_ != 200125) {
					autoSign.setSignstatus(1);
					autoSign.setSigntime(Timestamp.valueOf(FMT_FN.format(new Date())));
					long nextTime = new Date().getTime() + 1000 * 60 * 60 * 24;
					autoSign.setNextSigntime(Timestamp.valueOf(FMT_FN.format(nextTime)));
					long status = autoSignService.updateAccountInfo(autoSign);
					if(status == 1) {
						logger.info("手机号: " + autoSign.getPhone() +" , 签到成功!");
						
					}else {
						--COUNT;
						logger.error("编号: "+autoSign.getId()+" , 手机号: " + autoSign.getPhone() +" , 签到失败!");
					}
				}else {

					/* 签到失败就获取用户签到状态和时间 start **/
					String Result1 = signAdm.checkSignStatus(JSESSIONID);
					
					JSONObject jsonObject1 = JSONObject.parseObject(Result1);
					JSONObject jsonObjectdata = jsonObject1.getJSONObject("data");
					long times = jsonObjectdata.getLong("time");
					autoSign.setSignstatus(1);
					autoSign.setSigntime(Timestamp.valueOf(FMT_FN.format(times)));
					long nextTime = times + 1000 * 60 * 60 * 24;
					autoSign.setNextSigntime(Timestamp.valueOf(FMT_FN.format(nextTime)));
					autoSignService.updateAccountInfo(autoSign);
					
					logger.error(autoSign.getPhone() +" : "+ResultJson.toString());
				}
					
			}
			return Result.initSuccessResult("签到完成 " + COUNT + " 个用户, 共 " + list.size() + " 个用户! !!");
		}else {
			return Result.initSuccessResult("当前没有可签到的账户 !");
		}
	}

	/***
	 * 重置为可签到 
	 * errorCode : 5001
	 * @return
	 */
	@PostMapping("/updateSignStatus")
	public Result<String> updateSignStatus() {

		long count = autoSignService.updateSignStatus();

		if(count > 0) {
			return Result.initSuccessResult("重置账户为可签到状态 ! 时间 : " + FMT_FN.format(new Date()));
		}else {
			return Result.initFailureResult(5001, "重置账户为可签到状态 ! 时间 : " + FMT_FN.format(new Date()));
		}
	}

	
	/**
	 * 判断自动签到是否过期
	 * @return
	 */
	@PostMapping("/isAutoSign")
	public Result<Integer> isAutoSign(){
		int count = autoSignService.isAutoSign();
		return Result.initSuccessResult(count);
	}

	/**
	 * 判断农场喂养是否过期
	 * @return
	 */
	@PostMapping("/isAutoNC")
	public Result<Integer> isAutoNC(){
		int count = autoSignService.isAutoNC();
		return Result.initSuccessResult(count);
	}
}
